"""
AI分析配置管理服务
"""
import json
from typing import Dict, Any, List, Optional, Union
from datetime import datetime
from sqlalchemy.orm import Session
from sqlalchemy import and_, or_

from models.system import SystemConfig
from models.analysis_task import TaskType
from models.user import User
from core.database import get_db
from core.exceptions import ConfigurationError


class AIAnalysisConfigService:
    """AI分析配置管理服务类"""
    
    def __init__(self, db: Session):
        self.db = db
    
    def _get_config_key(self, task_type: str, config_key: str) -> str:
        """
        生成配置键名
        """
        return f"analysis_config.{task_type}.{config_key}"
    
    def _parse_config_value(self, config_value: str) -> Any:
        """
        解析配置值
        """
        try:
            return json.loads(config_value)
        except (json.JSONDecodeError, TypeError):
            return config_value
    
    def _serialize_config_value(self, config_value: Any) -> str:
        """
        序列化配置值
        """
        if isinstance(config_value, (dict, list)):
            return json.dumps(config_value, ensure_ascii=False)
        elif isinstance(config_value, bool):
            return json.dumps(config_value)
        return str(config_value)
    
    def get_config(self, task_type: str) -> Dict[str, Any]:
        """
        获取指定任务类型的配置
        """
        try:
            TaskType(task_type)  # 验证任务类型
        except ValueError:
            raise ConfigurationError(f"无效的任务类型: {task_type}")
        
        # 查询所有相关配置
        config_keys = [
            self._get_config_key(task_type, "analysis_levels"),
            self._get_config_key(task_type, "region_codes"),
            self._get_config_key(task_type, "enable_coordinate_analysis"),
            self._get_config_key(task_type, "prompt"),
            self._get_config_key(task_type, "filter_words")
        ]
        
        configs = self.db.query(SystemConfig).filter(
            SystemConfig.config_key.in_(config_keys),
            SystemConfig.is_active == True
        ).all()
        
        # 构建配置字典
        config_dict = {}
        for config in configs:
            key_parts = config.config_key.split(".")
            if len(key_parts) >= 3:
                config_key = key_parts[2]
                config_dict[config_key] = self._parse_config_value(config.config_value)
        
        return config_dict
    
    def save_config(self, task_type: str, config_data: Dict[str, Any], user: User) -> bool:
        """
        保存配置
        """
        try:
            TaskType(task_type)  # 验证任务类型
        except ValueError:
            raise ConfigurationError(f"无效的任务类型: {task_type}")
        
        # 验证配置数据
        self._validate_config_data(task_type, config_data)
        
        # 保存每个配置项
        for config_key, config_value in config_data.items():
            self._save_config_item(task_type, config_key, config_value, user)
        
        self.db.commit()
        return True
    
    def _save_config_item(self, task_type: str, config_key: str, config_value: Any, user: User):
        """
        保存单个配置项
        """
        config_key_full = self._get_config_key(task_type, config_key)
        
        # 查找现有配置
        existing_config = self.db.query(SystemConfig).filter(
            SystemConfig.config_key == config_key_full
        ).first()
        
        config_value_str = self._serialize_config_value(config_value)
        
        if existing_config:
            # 更新现有配置
            existing_config.config_value = config_value_str
            existing_config.last_modified_by = user.id
            existing_config.last_modified_at = datetime.now()
        else:
            # 创建新配置
            new_config = SystemConfig(
                config_key=config_key_full,
                config_name=f"{task_type} {config_key}",
                config_type="ai_analysis",
                config_value=config_value_str,
                description=f"AI分析配置 - {task_type}",
                last_modified_by=user.id,
                last_modified_at=datetime.now()
            )
            self.db.add(new_config)
    
    def _validate_config_data(self, task_type: str, config_data: Dict[str, Any]):
        """
        验证配置数据
        """
        if task_type == TaskType.RegionalAnalysis.value:
            self._validate_regional_analysis_config(config_data)
        elif task_type == TaskType.ComplaintTypeAnalysis.value:
            self._validate_complaint_type_config(config_data)
        elif task_type == TaskType.SentimentAnalysis.value:
            self._validate_sentiment_config(config_data)
        elif task_type == TaskType.ComplianceAnalysis.value:
            self._validate_compliance_config(config_data)
        elif task_type == TaskType.DuplicateAnalysis.value:
            self._validate_duplicate_config(config_data)
    
    def _validate_regional_analysis_config(self, config_data: Dict[str, Any]):
        """验证区域分析配置"""
        if "analysis_levels" not in config_data or not config_data["analysis_levels"]:
            raise ConfigurationError("区域分析级别不能为空")

        valid_levels = ["地市", "区县", "街道"]
        for level in config_data["analysis_levels"]:
            if level not in valid_levels:
                raise ConfigurationError(f"无效的区域分析级别: {level}")

        # 验证经纬度分析字段（如果存在）
        if "enable_coordinate_analysis" in config_data:
            # 如果是字符串，尝试转换为布尔值
            if isinstance(config_data["enable_coordinate_analysis"], str):
                if config_data["enable_coordinate_analysis"].lower() in ['true', '1', 'yes', 'on']:
                    config_data["enable_coordinate_analysis"] = True
                elif config_data["enable_coordinate_analysis"].lower() in ['false', '0', 'no', 'off', '']:
                    config_data["enable_coordinate_analysis"] = False
                else:
                    raise ConfigurationError("经纬度分析开关必须为布尔值")
            elif not isinstance(config_data["enable_coordinate_analysis"], bool):
                raise ConfigurationError("经纬度分析开关必须为布尔值")

        if "prompt" not in config_data or not config_data["prompt"].strip():
            raise ConfigurationError("提示词不能为空")
    
    def _validate_complaint_type_config(self, config_data: Dict[str, Any]):
        """验证信访类型分析配置"""
        if "prompt" not in config_data or not config_data["prompt"].strip():
            raise ConfigurationError("提示词不能为空")
    
    def _validate_sentiment_config(self, config_data: Dict[str, Any]):
        """验证情感分析配置"""
        if "prompt" not in config_data or not config_data["prompt"].strip():
            raise ConfigurationError("提示词不能为空")
    
    def _validate_compliance_config(self, config_data: Dict[str, Any]):
        """验证规范性分析配置"""
        if "prompt" not in config_data or not config_data["prompt"].strip():
            raise ConfigurationError("提示词不能为空")
    
    def _validate_duplicate_config(self, config_data: Dict[str, Any]):
        """验证重复信访分析配置"""
        if "filter_words" not in config_data or not config_data["filter_words"]:
            raise ConfigurationError("过滤词条不能为空")
        
        if len(config_data["filter_words"]) > 10:
            raise ConfigurationError("过滤词条数量不能超过10个")
        
        if "prompt" not in config_data or not config_data["prompt"].strip():
            raise ConfigurationError("提示词不能为空")
    
    def delete_config(self, task_type: str) -> bool:
        """
        删除配置
        """
        try:
            TaskType(task_type)  # 验证任务类型
        except ValueError:
            raise ConfigurationError(f"无效的任务类型: {task_type}")
        
        # 查找并删除相关配置
        config_pattern = f"analysis_config.{task_type}.%"
        configs = self.db.query(SystemConfig).filter(
            SystemConfig.config_key.like(config_pattern)
        ).all()
        
        for config in configs:
            config.is_active = False
        
        self.db.commit()
        return True
    
    def get_default_config(self, task_type: str) -> Dict[str, Any]:
        """
        获取默认配置
        """
        default_configs = {
            TaskType.RegionalAnalysis.value: {
                "analysis_levels": ["地市", "区县"],
                "region_codes": "",
                "enable_coordinate_analysis": False,
                "prompt": "请分析以下信访数据的地域分布特征，重点关注投诉热点区域和趋势变化。"
            },
            TaskType.ComplaintTypeAnalysis.value: {
                "prompt": "请对信访内容进行类型分类分析，识别主要的投诉类型和占比情况。"
            },
            TaskType.SentimentAnalysis.value: {
                "prompt": "请分析信访内容的情感倾向，包括正面、负面、中性情绪的分布和原因。"
            },
            TaskType.ComplianceAnalysis.value: {
                "prompt": "请评估信访答复的规范性，检查是否符合相关政策法规和标准格式要求。"
            },
            TaskType.DuplicateAnalysis.value: {
                "filter_words": ["重复", "再次", "又"],
                "prompt": "请识别重复或相似的信访内容，分析重复投诉的原因和模式。"
            }
        }
        
        return default_configs.get(task_type, {})
    
    def get_all_configs(self) -> List[Dict[str, Any]]:
        """
        获取所有配置
        """
        configs = []
        # 直接遍历任务类型的字符串值，避免枚举验证问题
        task_types = [
            "RegionalAnalysis",
            "ComplaintTypeAnalysis",
            "SentimentAnalysis",
            "ComplianceAnalysis",
            "DuplicateAnalysis"
        ]

        for task_type_value in task_types:
            try:
                config_data = self.get_config(task_type_value)
                configs.append({
                    "task_type": task_type_value,
                    "config_data": config_data,
                    "is_configured": bool(config_data)
                })
            except ConfigurationError:
                configs.append({
                    "task_type": task_type_value,
                    "config_data": {},
                    "is_configured": False
                })

        return configs
    
    def get_config_templates(self, task_type: str) -> List[Dict[str, Any]]:
        """
        获取配置模板
        """
        templates = []
        
        # 默认模板
        default_config = self.get_default_config(task_type)
        if default_config:
            templates.append({
                "template_name": "默认模板",
                "template_data": default_config,
                "description": "系统默认配置模板"
            })
        
        # TODO: 从数据库加载自定义模板
        # 这里可以扩展为从system_config表加载用户自定义模板
        
        return templates
    
    def validate_config(self, task_type: str, config_data: Dict[str, Any]) -> Dict[str, Any]:
        """
        验证配置
        """
        try:
            self._validate_config_data(task_type, config_data)
            return {
                "valid": True,
                "message": "配置数据验证通过"
            }
        except ConfigurationError as e:
            return {
                "valid": False,
                "message": str(e)
            }
    
    def batch_save_configs(self, configs: List[Dict[str, Any]], user: User) -> Dict[str, Any]:
        """
        批量保存配置
        """
        results = []
        success_count = 0
        
        for config in configs:
            task_type = config.get("task_type")
            config_data = config.get("config_data")
            
            if not task_type or not config_data:
                results.append({
                    "task_type": task_type or "unknown",
                    "status": "failed",
                    "message": "任务类型或配置数据不能为空"
                })
                continue
            
            try:
                self.save_config(task_type, config_data, user)
                results.append({
                    "task_type": task_type,
                    "status": "success",
                    "message": "保存成功"
                })
                success_count += 1
            except Exception as e:
                results.append({
                    "task_type": task_type,
                    "status": "failed",
                    "message": str(e)
                })
        
        return {
            "results": results,
            "total_count": len(configs),
            "success_count": success_count
        }